import controller from '../annotation/controller'
import router from '../annotation/router'
import MyInfo from '../entity/db1/myInfo';
import UserService from '../service/userService';
import { body, path, description, request, summary, tagsAll, responsesAll, query, prefix, header } from 'koa-swagger-decorator';
import { Context } from 'koa';
import jwtUtils from '../utils/jwtUtils';
import { HttpStatus } from '../middlewares/responseHandler';
import { File } from '../types/upload';
const userService = new UserService();

@tagsAll(['博主模块'])
@responsesAll({
    [HttpStatus.BAD_REQUEST]: {
        description: 'invalid parameter'
    },
    [HttpStatus.UNAUTHORIZED]: {
        description: 'invalid authorization',
    },
    [HttpStatus.OK]: {
        description: 'request success'
    }
})
@prefix('/user')
@controller({ path: '/user', name: '用户管理' })
export default class UserController {

    @header({ Authorization: { type: 'string', required: true, description: 'Bearer [token]' } })
    @request('get', '/myInfo/{id}')
    @path({ id: { type: 'number', required: true, description: '博主的id' } })
    @summary('博主info')
    @description('根据id查询博主信息')
    @router({ method: 'get', path: '/myInfo/:id', name: '博主信息' })
    public async getMyInfo(ctx: Context) {
        const { id } = ctx.params;
        const myInfo = await userService.findMyInfoById(Number(id))
        if (!myInfo) {
            return {
                data: {
                    status: HttpStatus.NOT_FOUND,
                    msg: '该博主不存在'
                }
            };
        }
        return {
            data: {
                status: HttpStatus.OK,
                myInfo
            }
        }
    }

    @request('get', '/login')
    @query({
        username: { type: 'string', required: true, description: '用户名' },
        verifyCode: { type: 'string', required: true, description: '验证码' }
    })
    @summary('用户登录')
    @description('登录接口啦')
    @router({ method: 'get', path: '/login', name: '登录接口' })
    public async login(ctx: Context) {
        const { username, verifyCode } = ctx.request.query;
        if (verifyCode && ctx.session.captcha && verifyCode === ctx.session.captcha) {
            ctx.session.captcha = '';
            const record = await userService.findByUsername(username as string);
            if (record) {
                const token = jwtUtils.auth(ctx, {
                    id: record.id,
                })
                return {
                    status: HttpStatus.OK,
                    data: {
                        msg: '授权成功',
                        id: record.id,
                        username,
                        token
                    }
                }
            }
            return {
                status: HttpStatus.OK,
                data: {
                    msg: '用户名或密码有误'
                }
            }
        }
        return {
            status: HttpStatus.OK,
            data: {
                msg: ' 验证码有误'
            },
        };
    }

    @body((MyInfo as any).swaggerDocument)
    @router({ method: 'post', path: '/addUper', name: '新增博主' })
    public async addUper(ctx: Context) {
        const body = ctx.request.body;
        const myInfo = new MyInfo({
            uName: body?.uName,
            qq: body?.qq,
            githubUrl: body?.githubUrl,
            content: body?.content
        })
        const newRecord = await userService.addMyInfo(myInfo);
        return {
            status: HttpStatus.CREATE,
            data: {
                myInfo: newRecord
            },
        };
    }

    @router({ method: 'post', path: '/updateUper', name: '更新博主' })
    public async updateUper(ctx: Context) {
        const body = ctx.request.body;
        const affectRowCount = await userService.updateMyInfoById(new MyInfo({
            id: body?.id,
            uName: body?.uName,
            qq: body?.qq,
            githubUrl: body?.githubUrl,
            content: body?.content
        }))
        if (affectRowCount > 0) {
            return {
                status: HttpStatus.OK,
                data: {
                    msg: '更新成功'
                }
            };
        }
        return {
            status: HttpStatus.OK,
            data: {
                msg: '更新失败'
            }
        }
    }

    @router({ method: 'post', path: '/deleteUper', name: '删除博主' })
    public async deleteUperById(ctx: Context) {
        const { id } = ctx.request.body;
        try {
            const affectRecord = await userService.deleteUperById(id)
            return {
                status: HttpStatus.OK,
                data: {
                    msg: '删除成功',
                    affectRecord
                }
            }
        } catch (error) {
            return {
                status: HttpStatus.OK,
                data: {
                    msg: `删除失败:${error}`,
                }
            }
        }
    }

    @router({ method: 'post', path: '/uploadAvatar', name: '用户头像上传' })
    public async uploadAvatar(ctx: Context) {
        const file = ctx.request.files?.file as File;
        if (!file) {
            return {
                status: HttpStatus.BAD_REQUEST,
                msg: '请检查文件字段'
            }
        }
        try {
            const avatarUrl = userService.saveFile(file);
            return {
                status: HttpStatus.OK,
                data: {
                    avatarUrl
                }
            }
        } catch (error) {
            return {
                status: HttpStatus.BAD_REQUEST,
                data: {
                    msg: `上传失败: ${error}`
                }
            }
        }
    }
}